package cn.zou.blog.controller;

import java.util.Date;
import java.util.UUID;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.zou.blog.entry.Shuo;
import cn.zou.blog.service.ShuoService;
import cn.zou.core.page.Page;
/**
 * 闲言碎语层
 * @author zoujing
 *
 */
@Controller
@RequestMapping("/shuo")
public class ShuoController {
	@Autowired
	private ShuoService shuoService;
	/**
	 * 页面跳转
	 * @return
	 */
	@RequestMapping("/shuoUI.shtml")
	public String shouUI(Page<Shuo> page,ModelMap map){
		page = shuoService.findShuos(page);
		map.put("page",page);
		return "shuo";
	}
	/**
	 * 后台页面
	 * @param map
	 * @param page
	 * @return
	 */
	@RequestMapping("/admin/toShuoUI.shtml")
	public String toShuoUI(ModelMap map,Page<Shuo> page){
		map.addAttribute("page", shuoService.findShuos(page));
		return "admin/shuo/admin_ShuoUI";
	}
	/**
	 * 异步更新文章
	 * @param response
	 * @param content
	 * @param id
	 */
	@RequestMapping("/admin/updateShuo.shtml")
	public void updateShuo(HttpServletResponse response,String content,String id){
		try {
			response.setContentType("text/html");
			ServletOutputStream outputStream = response.getOutputStream();
			if(StringUtils.isNotBlank(id)){
				Shuo shuo= shuoService.findShuoByid(id);
				if(shuo.getContent().equals(content)){
					outputStream.write("不需要更新".getBytes("utf-8"));
				}else{
					shuo.setContent(content);
					shuoService.updateShuo(shuo);
					outputStream.write("更新成功".getBytes("utf-8"));
				}
				
			}else{
				outputStream.write("更新失败".getBytes("utf-8"));
			}
			outputStream.close();
		} catch (Exception e) {
			
			e.printStackTrace();
		}
		
	}
	/**
	 * 删除一条说说
	 * @param id
	 * @param pageNo
	 * @param map
	 * @return
	 */
	@RequestMapping("/admin/deleteShuo.shtml")
	public String deleteShuo(String id,int pageNo,ModelMap map){
		if(StringUtils.isNotBlank(id)){
			shuoService.deleteShuo(id);
		}
		map.addAttribute("pageNo", pageNo);
		return "redirect:toShuoUI.shtml";
	}
	/**
	 * 添加一条说说
	 */
	@RequestMapping("/admin/addShuo.shtml")
	public String addShuo(String content,ModelMap map){
		if(StringUtils.isNotBlank(content)){
			Shuo shuo=new Shuo();
			shuo.setId(UUID.randomUUID().toString().replace("-", ""));
			shuo.setContent(content);
		    shuo.setCreateTime(new Date());
		    shuoService.AddShuo(shuo);
		}
		map.addAttribute("pageNo",0);
		return "redirect:toShuoUI.shtml";
	}
}
